package com.lu.widgets.component.ime;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.lu.widgets.R;
import com.lu.widgets.component.animation.iTranslateAnimation;

public class QwertyIME extends RelativeLayout implements IIMEAnimation {
	private QwertyIMEWithoutMask qwerty;
	private iTranslateAnimation imeAnimation;
	private View mask;

	public QwertyIME(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		LayoutInflater.from(context).inflate(R.layout.qwerty_ime, this, true);
		if (!isInEditMode()) {
			findAllView();
			setListener();
			setDefaultProperties();
			TypedArray a = context.obtainStyledAttributes(attrs,
					R.styleable.IME, defStyle, 0);
			android.view.ViewGroup.LayoutParams lp = qwerty.getLayoutParams();
			lp.height = a.getDimensionPixelSize(R.styleable.IME_qwerty_height,
					228);
			qwerty.setLayoutParams(lp);
			mask.setVisibility(a.getBoolean(R.styleable.IME_enableMask, true) ? VISIBLE
					: GONE);
			a.recycle();
		}
	}

	public QwertyIME(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public QwertyIME(Context context) {
		this(context, null, 0);
	}

	public void setTag(EditText editText) {
		qwerty.setTag(editText);
		editText.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				v.performClick();
				v.requestFocus();
				display();
				return true;
			}
		});
	}

	protected void findAllView() {
		mask = (View) findViewById(R.id.mask);
		qwerty = (QwertyIMEWithoutMask) findViewById(R.id.qwerty);
		imeAnimation = new iTranslateAnimation(getContext(), qwerty, 0, 300,
				this, false);
	}

	protected void setDefaultProperties() {
		setVisibility(GONE);
		qwerty.enableChangeBtn(false);
		imeAnimation.setEnableParent(true);
	}

	protected void setListener() {
		setOnMaskClickListener(null);
	}

	public void setOnMaskClickListener(final OnClickListener l) {
		mask.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				hide();
				if (l != null)
					l.onClick(v);
			}
		});
	}

	public boolean performMaskClick() {
		return mask.performClick();
	}

	@Override
	public boolean change() {
		return false;
	}

	@Override
	public boolean display() {
		setVisibility(VISIBLE);
		imeAnimation.flyIn();
		return true;
	}

	@Override
	public boolean hide() {
		imeAnimation.flyOut();
		return true;
	}
}
